﻿using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Read.API.Application.Command.PatientCommand;
using MediatR;

namespace D.Medicalcare.Read.API.Application.Handler.PatientHandler
{
    /// <summary>
    /// 获取默认就诊人
    /// </summary>
    public class GetPatientMHandler : IRequestHandler<GetPatientMCommand, APIResult<Patient>>
    {
        private readonly IBaseRepository<Patient> prep;
        private readonly ILogger<GetPatientMHandler> logger;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="prep">仓储</param>
        /// <param name="logger">日志</param>
        public GetPatientMHandler(IBaseRepository<Patient> prep, ILogger<GetPatientMHandler> logger)
        {
            this.prep = prep;
            this.logger = logger;
        }
        /// <summary>
        /// 处理
        /// </summary>
        public async Task<APIResult<Patient>> Handle(GetPatientMCommand request, CancellationToken cancellationToken)
        {
            APIResult<Patient> result = new APIResult<Patient>();
            try
            {
                var list = prep.GetAll().Where(x=>x.ParentId==request.ParentId);
                if (request.IsDefault!=null)
                {
                    list.Where(x=>x.IsDefault==request.IsDefault);
                }
                result.Code = APIEnum.Success;
                result.Msg = "查询成功";
                logger.LogInformation(result.Msg);
                result.Data = list.FirstOrDefault();
                return await Task.FromResult(result);
            }
            catch (Exception ex)
            {
                logger.LogError("查询异常" + ex.Message);

                throw;
            }

        }
    }
}
